package me.landery.modules.sinco.service.impl;

import lombok.RequiredArgsConstructor;
import me.landery.exception.BadRequestException;
import me.landery.modules.sinco.domain.Application;
import me.landery.modules.sinco.service.ApplicationService;
import me.landery.modules.sinco.service.AuthenticationService;
import me.landery.modules.sinco.service.dto.AuthenticationDto;
import me.landery.modules.sinco.util.AppUtils;
import me.landery.utils.RedisUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthenticationServiceImpl implements AuthenticationService {

    private final RedisUtils redisUtils;
    private final ApplicationService applicationService;

    @Override
    public AuthenticationDto getAuthToken(String appId, String secretkey) {
        // 校验appId和secret
        Application application = applicationService.getByAppId(appId);
        if (application == null) {
            throw new BadRequestException("应用不存在");
        }
        if (!application.getSecretkey().equals(secretkey)) {
            throw new BadRequestException("应用密钥错误");
        }

        //判断应用状态
        if (application.getStatus() == 0) {
            throw new BadRequestException("应用已禁用");
        }

        //判断appId对应的token是否存在
        //如果存在，则判断token是否过期
        String token = (String)redisUtils.get(appId);

        //如果token为空，则生成token
        if (token == null) {
            token =  AppUtils.sha256(appId + secretkey);
            //有效时间为2小时
            redisUtils.set(appId, token, 7200);
        }
        AuthenticationDto authenticationDto= new  AuthenticationDto();
        authenticationDto.setAppId(appId);
//        authenticationDto.setSecretKey(secretkey);
        authenticationDto.setToken(token);
        return authenticationDto;
    }
}
